package com.caiheng.api.controller.mer;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.vdurmont.emoji.EmojiParser;
import com.caiheng.api.constant.ResponseCode;
import com.caiheng.api.controller.platform.BaseController;
import com.caiheng.api.entity.attendance.AttendanceGroupUser;
import com.caiheng.api.entity.dto.ProductTypeDto;
import com.caiheng.api.entity.dto.WalletDto;
import com.caiheng.api.entity.mer.*;
import com.caiheng.api.entity.platform.*;
import com.caiheng.api.entity.product.OrderAppraise;
import com.caiheng.api.entity.product.Product;
import com.caiheng.api.entity.product.ProductOrder;
import com.caiheng.api.entity.sys.SysUser;
import com.caiheng.api.entity.wxuser.User;
import com.caiheng.api.entity.wxuser.UserMerCoupon;
import com.caiheng.api.service.platfom.*;
import com.caiheng.api.service.product.OrderAppraiseService;
import com.caiheng.api.service.product.ProductOrderService;
import com.caiheng.api.service.product.ProductService;
import com.caiheng.api.service.product.ProductTypeService;
import com.caiheng.api.service.sys.SysErrorService;
import com.caiheng.api.service.sys.SysUserService;
import com.caiheng.api.service.wxuser.UserCollectionService;
import com.caiheng.api.service.wxuser.UserMerCouponService;
import com.caiheng.api.service.wxuser.UserMpService;
import com.caiheng.api.service.wxuser.UserService;
import com.caiheng.api.service.mer.*;
import com.caiheng.api.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 *@Author: ZhouWei
 *@Description:  用户技能相关接口
 *@Date 2018-05-10
 */
@Component
@RestController
@RequestMapping("/mer")//url:模块/资源/{}/细分
public class MerController extends BaseController {

    @Resource
    private MerService merService;
    @Resource
    private MerCouponService merCouponService;
    @Resource
    private UserMerCouponService userMerCouponService;
    @Resource
    private MerUserService merUserService;
    @Resource
    private OrderAppraiseService orderAppraiseService;
    @Resource
    private ProductService productService;
    @Resource
    private ProductOrderService productOrderService;
    @Resource
    private ProductTypeService productTypeService;
    @Resource
    private UserService userService;
    @Resource
    private SysErrorService sysErrorService;
    @Resource
    private SysUserService sysUserService;
    @Resource
    private UserCollectionService userCollectionService;
    @Resource
    private SearchDataService searchDataService;
    @Resource
    private ProvinceService provinceService;
    @Resource
    private CityService cityService;
    @Resource
    private DistrictService districtService;

    @Value("${web.imgPrefix}")
    private String imgPrefix;//图片地址

    @Value("${web.uploadPath}")
    private String uploadPath;//图片地址


    /**
     * 充电测试
     * @return
     */
    @PostMapping(value = "/test")
    public JSONObject test(@RequestBody String requestParam, HttpServletRequest request){
        JSONObject ret = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

//            List<UserMp> users = userMpService.selectUserMpList(mer_id);
//            merCategoryService.resetCategory();

            ret = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功" ),true,false);

        }catch (Exception e){
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/list")
    public JSONObject list(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            int cateId = jsonRequest.containsKey("cate_id") ? jsonRequest.getInt("cate_id") : 0;
            int cateChildId = jsonRequest.containsKey("cate_child_id") ? jsonRequest.getInt("cate_child_id") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String sort = jsonRequest.containsKey("sort") ? jsonRequest.getStr("sort") : null;

            int offset = (pageIndex - 1) * pageSize;
            List<Mer> list = merService.selectByState(user_id,0,cateId,cateChildId,keyword,0,sort,offset,pageSize,longitude,latitude);
            Map<String,Object> map = new HashMap<>();
            map.put("mers",list);

            List<ProductTypeDto> types = productTypeService.getChildOptions(cateId,cateChildId);
            map.put("serviceTypes",types);

            if(CollUtil.isNotEmpty(list)){
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",0,map),false,false);
            }
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/search/list")
    public JSONObject searchList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/search/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int userId = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex") && StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;
            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude") : 0;
            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude") : 0;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;


            if(StrUtil.isNotEmpty(keyword)){
                SearchData searchData = new SearchData();
                searchData.setCreateTime(new Date());
                searchData.setFromType("mer");
                searchData.setUserId(userId);
                searchData.setSearchWord(keyword);
                searchDataService.save(searchData);
            }

            List<Mer> list = merService.getListBySearch(userId,keyword,shop_type,pageIndex,pageSize,longitude,latitude);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/coupon/list")
    public JSONObject couponList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/coupon/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

            Mer mer = merService.findById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该商家不存在"),true,true);
            }

            QueryWrapper<MerCoupon> qw = new QueryWrapper<>();
            qw.eq("mer_id",mer_id);
            qw.eq("state",1);
            List<MerCoupon> list = merCouponService.list(qw);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),list),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/coupon/detail")
    public JSONObject couponDetail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/coupon/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer coupon_id = jsonRequest.containsKey("coupon_id") ? jsonRequest.getInt("coupon_id") : 0;

            MerCoupon merCoupon = merCouponService.findById(coupon_id);
            if(merCoupon != null){
                if(StrUtil.isNotEmpty(merCoupon.getImgUrl())){
                    merCoupon.setImgUrl(imgPrefix + merCoupon.getImgUrl());
                }
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",merCoupon),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 用户的 商家的优惠券列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/coupon/user/list")
    public JSONObject couponUserList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/coupon/user/list 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该用户不存在"),true,true);
            }

            QueryWrapper<UserMerCoupon> qw = new QueryWrapper<>();
            qw.eq("user_id",user_id);
            qw.orderByDesc("id");
            List<UserMerCoupon> list = userMerCouponService.getPageEntityList(qw,pageIndex,pageSize);

            Map<String,Object> map = new HashMap<>();
            map.put("coupons",list);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(),map),false,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  申请生成 领蛋结算单
     * @param
     * @throws Exception
     */
    @PostMapping(value="/update/bankInfo")
    public JSONObject updateBankInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/update/bankInfo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            String bank_name = jsonRequest.containsKey("bank_name") ? jsonRequest.getStr("bank_name") : "";
            String card_num = jsonRequest.containsKey("card_num") ? jsonRequest.getStr("card_num") : "";
            String real_name = jsonRequest.containsKey("real_name") ? jsonRequest.getStr("real_name") : "";

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"该用户不存在"),true,true);
            }

            Mer mer = merService.findById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"您商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id,mer_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"您没有该权限"),true,true);
            }

            if(merUser.getIsAdmin() == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"您没有该商家的管理权限"),true,true);
            }

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 我的商家列表
     * @param
     * @throws Exception
     */
    @PostMapping(value="/myList")
    public JSONObject myList(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/myList 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            Integer user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 1;
            Integer shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;
            Integer pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString()) ? jsonRequest.getInt("pageIndex") : 1;
            Integer pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString()) ? jsonRequest.getInt("pageSize") : 10;

            int offset = (pageIndex - 1) * pageSize;

            List<Map<String,Object>> merNames = new ArrayList<>();
            List<Mer> list = merService.selectMyList(user_id,shop_type,offset,pageSize);
            if(CollUtil.isNotEmpty(list)){
                for (Mer mer : list){
                    Map<String,Object> map1 = new HashMap<>();
                    map1.put("text",mer.getShopName());
                    map1.put("value",mer.getId());
                    merNames.add(map1);
                    if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                        mer.setShopLogo(imgPrefix + mer.getShopLogo());
                    }
                }
            }
            map.put("mer_names",merNames);
            map.put("mers",list);
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",list.size(), map),false,false);
        }catch (Exception e){
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  移交商家给其他人
     * @param
     * @throws Exception
     */
    @PostMapping(value="/exChangeUser")
    public JSONObject exChangeUser(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/exChangeUser 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int exchange_user_id = jsonRequest.containsKey("exchange_user_id") ? jsonRequest.getInt("exchange_user_id") : 0;

            if(exchange_user_id == 0){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"请选择移交用户"),true,true);
            }
            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }


            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id, mer_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"无移交权限"),true,true);
            }

            User exchangUser = userService.findById(exchange_user_id);
            if(exchangUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"移交用户不存在"),true,true);
            }

            SysUser sysUser = sysUserService.findById(user.getSysUserId());
            if(sysUser!=null){
                merUser.setSysUserId(sysUser.getUserId());
            }

            merUser.setUserId(exchange_user_id);
            merUser.setNickName(exchangUser.getNickName());
            boolean bl = merUserService.updateById(merUser);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"移交成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"移交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     *  存在多个商家的情况下，设置默认的显示商家
     * @param
     * @throws Exception
     */
    @PostMapping(value="/changeDefault")
    public JSONObject changeDefault(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/exChangeUser 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            MerUser merUser = merUserService.getMerByUser(user_id, mer_id);
            if(merUser == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"暂无该商家权限"),true,true);
            }

            List<MerUser> merUsers = merUserService.selectListByColumn("user_id",user_id);
            if(CollUtil.isNotEmpty(merUsers)){
                for(MerUser merUser1 : merUsers){
                    //先重置 默认状态 都未0
//                    merUserService.update(merUser1,new LambdaUpdateWrapper<MerUser>()
//                            .set(MerUser::getIsDefault, 0).eq(MerUser::getUserId, merUser1.getUserId()));
                    merUser1.setIsDefault(0);
                    merUserService.updateById(merUser1);
                }
            }

            merUser.setIsDefault(1);
            boolean bl = merUserService.updateById(merUser);
            if(bl) {
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"切换成功"),true,true);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"切换失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家详情信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detail")
    public JSONObject detail(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/detail 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : 0;
            int pageIndex = jsonRequest.containsKey("pageIndex")&& StrUtil.isNotEmpty(jsonRequest.get("pageIndex").toString())  ? jsonRequest.getInt("pageIndex") : 1;
            int pageSize = jsonRequest.containsKey("pageSize")&& StrUtil.isNotEmpty(jsonRequest.get("pageSize").toString())  ? jsonRequest.getInt("pageSize") : 10;

            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                mer.setShopLogo(imgPrefix + mer.getShopLogo());
            }

            //获取商家的服务（商品）
            List<Product> products = productService.queryProductList(mer.getId(),0);
            mer.setProducts(products);
            mer.setProductCount(products.size());

            QueryWrapper<MerCoupon> qw = new QueryWrapper<>();
            qw.eq("mer_id",mer_id);
            qw.eq("state",1);
            List<MerCoupon> coupons = merCouponService.list(qw);
            if(CollUtil.isNotEmpty(coupons)){
                for (MerCoupon merCoupon : coupons){
                    if(StrUtil.isNotEmpty(merCoupon.getImgUrl())){
                        merCoupon.setImgUrl(imgPrefix + merCoupon.getImgUrl());
                    }
                }
            }
            mer.setCoupons(coupons);

            List<OrderAppraise> appraises = orderAppraiseService.selectByMerId(mer_id,pageIndex,pageSize);
            map.put("mer",mer);
            map.put("appraises",appraises);
            map.put("appraiseCount",0);
            map.put("user_id",user_id);

            map.put("isCollect",0);
            long isCollect = userCollectionService.getCollectionCountByMerId(user_id,mer_id);
            if(isCollect > 0){
                map.put("isCollect",1);
            }

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家详情信息
     * @param
     * @throws Exception
     */
    @PostMapping(value="/detailByNo")
    public JSONObject detailByNo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/detailByNo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shop_no = jsonRequest.containsKey("shop_no") ? jsonRequest.getStr("shop_no") : null;
//            double longitude = jsonRequest.containsKey("longitude") ? jsonRequest.getDouble("longitude"): 0;
//            double latitude = jsonRequest.containsKey("latitude") ? jsonRequest.getDouble("latitude"): 0;

//            User user = userService.findById(user_id);
//            if(user == null) {
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
//            }

            if(shop_no == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }

            Mer mer = merService.selectByUniqueColumn("shop_no",shop_no);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
            }

            if(StrUtil.isNotEmpty(mer.getShopLogo())) {
                mer.setShopLogo(imgPrefix + mer.getShopLogo());
            }

            map.put("mer",mer);

//            map.put("is_has_pay_pwd", 0);
//            if(StrUtil.isNotEmpty(user.getPayPwd())){
//                map.put("is_has_pay_pwd", 1);
//            }

//            double distance = GetDistance.GetDistance(mer.getLongitude().doubleValue(),mer.getLatitude().doubleValue(),longitude,latitude);
//            map.put("distance", distance);

            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家钱包界面详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/myMerInfo")
    public JSONObject myMerInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/myMerInfo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            int shop_type = jsonRequest.containsKey("shop_type") ? jsonRequest.getInt("shop_type") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            MerUser merUser = merUserService.getDefaultMerUser(user_id);

            long orderCount = 0;
            double fee = 0d, payPrice = 0d, totalPrice = 0;
            WalletDto walletDto = new WalletDto();
            int index = 0;

            List<Map<String,Object>> merActions = new ArrayList<>();
            List<Mer> list = merService.selectMyList(user_id,shop_type,0,100);
            if(CollUtil.isNotEmpty(list)){
                for (Mer mer : list){
                    if(merUser!= null){
                        if(merUser.getMerId().intValue() == mer.getId().intValue()){
                            map.put("mer_name",mer.getShopName());
                            map.put("mer_id",mer.getId());
                            map.put("shop_type",mer.getShopType());
                        }
                    }else{
                        if(index == 0){
                            map.put("mer_name",mer.getShopName());
                            map.put("mer_id",mer.getId());
                            map.put("shop_type",mer.getShopType());
                        }
                    }

                    Map<String,Object> sheetOption = new HashMap<>();
                    sheetOption.put("mer_id", mer.getId());
                    sheetOption.put("name", mer.getShopName());
                    sheetOption.put("shop_type", mer.getShopType());
                    merActions.add(sheetOption);

//                    if(shop_type == 0){
//                        //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
//                        // 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
//                        Integer[] states = new Integer[]{ 2 , 3 ,4};
//                        QueryWrapper<ProductOrder> qwOrder = new QueryWrapper<>();
//                        qwOrder.select("id");
//                        qwOrder.eq("mer_id",mer.getId());
//                        qwOrder.in("status",states);
//                        long temp_orderCount = productOrderService.count(qwOrder);
//                        orderCount = orderCount + temp_orderCount;
//
//                        Map<String,Object> mapTotal = new HashMap<>();
//                        mapTotal.put("merId",mer.getId());
//                        mapTotal.put("beginTime", DateUtil.getMonthFirstDay() + " 00:00:00");
//                        mapTotal.put("endTime",new Date());
//                        walletDto = productOrderService.getAllMoneyByMerIdAndTime(mapTotal);
//                        if(walletDto == null){
//                            walletDto = new WalletDto();
//                            walletDto.setFee(0d);
//                            walletDto.setPayPrice(0d);
//                            walletDto.setTotalPrice(0d);
//                        }else{
//                            fee = fee +  walletDto.getFee();
//                            payPrice = payPrice + walletDto.getPayPrice();
//                            totalPrice = totalPrice + walletDto.getTotalPrice();
//                        }
//                    }
                    index++;
                }
            }


            if(merUser!= null){
                //订单状态订单状态 0 - 未支付   1 - 支付中  2 - 已支付（待核销）  3 - 已核销  4 - 已评价
                // 5 - 订单取消  6 - 发起退货  7 - 同意退货  8 - 退货完成  9 - 拒绝退货
                Integer[] states = new Integer[]{ 2 , 3 ,4};
                QueryWrapper<ProductOrder> qwOrder = new QueryWrapper<>();
                qwOrder.select("id");
                qwOrder.eq("mer_id", merUser.getMerId());
                qwOrder.in("status",states);
                long temp_orderCount = productOrderService.count(qwOrder);
                orderCount = orderCount + temp_orderCount;

                Map<String,Object> mapTotal = new HashMap<>();
                mapTotal.put("merId", merUser.getMerId());
                mapTotal.put("beginTime", DateUtil.getMonthFirstDay() + " 00:00:00");
                mapTotal.put("endTime",new Date());
                walletDto = productOrderService.getAllMoneyByMerIdAndTime(mapTotal);
                if(walletDto == null){
                    walletDto = new WalletDto();
                    walletDto.setFee(0d);
                    walletDto.setPayPrice(0d);
                    walletDto.setTotalPrice(0d);
                }else{
                    if(walletDto.getFee() != null){
                        fee = fee +  walletDto.getFee();
                    }
                    payPrice = payPrice + walletDto.getPayPrice();
                    totalPrice = totalPrice + walletDto.getTotalPrice();
                }
            }


            walletDto = new WalletDto();
            walletDto.setFee(MathUtil.getDoubleUp(fee));
            walletDto.setPayPrice(MathUtil.getDoubleUp(payPrice));
            walletDto.setTotalPrice(MathUtil.getDoubleUp(totalPrice));

            map.put("order_count",orderCount);
            map.put("mer_count",list.size());
            map.put("mers",list);
            map.put("merActions",merActions);
            map.put("wallet",walletDto);


            if(StrUtil.isNotEmpty(user.getFaceUrl())){
                if(!user.getFaceUrl().contains("https")){
                    map.put("face_url", imgPrefix + user.getFaceUrl());
                }else{
                    map.put("face_url",  user.getFaceUrl());
                }
            }
            map.put("nick_name", "");
            if(StrUtil.isNotEmpty(user.getNickName())){
                map.put("nick_name", EmojiParser.parseToUnicode(user.getNickName()));
            }
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);

        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家钱包界面详情
     * @param
     * @throws Exception
     */
    @PostMapping(value="/walletInfo")
    public JSONObject walletInfo(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/walletInfo 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            Integer mer_id = jsonRequest.containsKey("mer_id") ? jsonRequest.getInt("mer_id") : null;
//            int pageIndex = jsonRequest.containsKey("pageIndex") ? jsonRequest.getInt("pageIndex") : 1;
//            int pageSize = jsonRequest.containsKey("pageSize") ? jsonRequest.getInt("pageSize") : 10;


            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }

            if(mer_id != null){
                Mer mer = merService.getById(mer_id);
                if(mer == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"商家不存在"),true,true);
                }

                MerUser merUser = merUserService.getMerByUser(user_id,mer_id);
                if(merUser == null){
                    return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"没有该商家权限"),true,true);
                }
                map = merService.getWalletDaysData(user_id,mer_id);
                map.put("mer_name",mer.getShopName());
            }


            result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"成功",map),true,false);
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /**
     * 商家入驻
     * @param
     * @throws Exception
     */
    @PostMapping(value="/register")
    public JSONObject register(@RequestBody String requestParam) throws Exception{
        JSONObject result = null;
        Map<String,Object> map = new HashMap<>();
        try{
            if(StrUtil.isEmpty(requestParam)){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"参数异常"),true,true);
            }
            logBefore(logger, "mer/register 接收的参数： "+requestParam);
            JSONObject jsonRequest = JSONUtil.parseObj(requestParam);
            int user_id = jsonRequest.containsKey("user_id") ? jsonRequest.getInt("user_id") : 0;
            String shopName = jsonRequest.containsKey("shopName") ? jsonRequest.getStr("shopName") : null;
            String leaderName = jsonRequest.containsKey("leaderName") ? jsonRequest.getStr("leaderName") : null;
            String phoneNum = jsonRequest.containsKey("phoneNum") ? jsonRequest.getStr("phoneNum") : null;
            String keyword = jsonRequest.containsKey("keyword") ? jsonRequest.getStr("keyword") : null;
            String address = jsonRequest.containsKey("address") ? jsonRequest.getStr("address") : null;
            int ag_id = jsonRequest.containsKey("ag_id") ? jsonRequest.getInt("ag_id") : 0;

            double lng = jsonRequest.containsKey("lng") ? jsonRequest.getDouble("lng") : 0;
            double lat = jsonRequest.containsKey("lat") ? jsonRequest.getDouble("lat") : 0;

            User user = userService.findById(user_id);
            if(user == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"该用户不存在"),true,true);
            }


            Mer mer = merService.getMerByUserIdUnCheck(user_id);
            if(mer != null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您有待审核的商家，请耐心等待"),true,true);
            }

//            MerUser merUser = merUserService.getMerUser(user_id);
//            if(merUser != null){
//                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"您已申请商家"),true,true);
//            }

            mer = new Mer();
            String shopNo = "M" + new Date().getTime();
//            mer.setUserId(user_id);
            mer.setShopNo(shopNo);
            mer.setShopName(shopName);
            mer.setShopType(0);
            mer.setState(1);
            mer.setCateId(2);
            mer.setLongitude(new BigDecimal(lng));
            mer.setLatitude(new BigDecimal(lat));
            mer.setCreateTime(new Date());
            mer.setAddress(address);
            mer.setKeyWord(keyword);
            mer.setLeaderName(leaderName);
            mer.setTelphone(phoneNum);
            mer.setServiceStar(0);
            mer.setMaxOrderCount(1000);
            mer.setIsPlatform(0);
            mer.setCheckState(0);



            Province province = provinceService.selectByUniqueColumn("province_name",user.getProvince());
            if(province!=null){
                mer.setProvId(province.getId());
                QueryWrapper<City> qwCity = new QueryWrapper<>();
                qwCity.eq("province_id",province.getId());
                qwCity.like("city_name", user.getCity());
                qwCity.last("limit 1");
                City city = cityService.getOne(qwCity);
                if(city!=null){
                    mer.setCityId(city.getId());
                    if(StrUtil.isNotEmpty(user.getDistrict())){
                        QueryWrapper<District> qwDis = new QueryWrapper<>();
                        qwDis.eq("city_id",city.getId());
                        qwDis.like("district_name", user.getDistrict());
                        qwDis.last("limit 1");
                        District district = districtService.getOne(qwDis);
                        if(district!=null){
                            mer.setDistrictId(district.getId());
                        }
                    }
                }
            }

            mer = merService.getLocationInfo(mer);

            int ret = merService.register(mer,user,ag_id);
            if(ret > 0){

                result = Tools.getJson(new GsonResultBean<>(ResponseCode.OK,"已提交申请",mer.getId()),true,false);
            }else{
                result = Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL,"提交失败"),true,true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            System.out.println(e.getMessage());
            logger.error(e.getMessage(), e);
        }
        return result;
    }

    /** 商家入驻的图片上传
     * @param
     * @throws Exception
     */
    @PostMapping(value="/uploadImg")
    public JSONObject uploadImgRepair(@RequestParam("mer_id") int mer_id,@RequestParam("type") int type, HttpServletRequest request) throws Exception{
        JSONObject result = null;
        try{
            Mer mer = merService.getById(mer_id);
            if(mer == null){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "商家不存在"), true, true);
            }

            // 创建一个通用的多部分解析器.
            CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 设置编码
            commonsMultipartResolver.setDefaultEncoding("utf-8");
            // 判断是否有文件上传
            String imgUrls= "";
            if (commonsMultipartResolver.isMultipart(request)) {//有文件上传
                //将request变成多部分request
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
                //获取multiRequest 中所有的文件名
                Iterator<String> iter = multiRequest.getFileNames();
                if (iter.hasNext()) {
                    Map<String, MultipartFile> maps = multiRequest.getFileMap();
                    for(String key : maps.keySet()) {
                        MultipartFile certUrl = maps.get(key);
                        if (!certUrl.isEmpty()) {
                            String prefix = certUrl.getOriginalFilename().substring(certUrl.getOriginalFilename().lastIndexOf(".") + 1);
                            if ("jpeg".equals(prefix) || "jpg".equals(prefix) || "png".equals(prefix)) {
                                String fileName = "shop_img_" + new Date().getTime() + "." + prefix;// user_photo.getOriginalFilename();
                                try {
                                    byte[] byteImg = certUrl.getBytes();
                                    if (byteImg != null) {
                                        //上传头像到OSS
                                        int upload_type = OssUtil.TYPE_MER_PHOTOS;
                                        String img_key = OssUtil.getUploadPrefix(upload_type) + fileName;


                                        String filePath = uploadPath + img_key;
                                        FileOutputStream out = new FileOutputStream(filePath);
                                        out.write(certUrl.getBytes());
                                        out.flush();
                                        out.close();

                                        ImagesFiler.imageResize(filePath,filePath);

                                        OssUtil.uploadObs(certUrl.getInputStream(),fileName,upload_type);

                                        imgUrls += img_key + ",";
                                    }
                                } catch (IOException e) {
                                    e.printStackTrace();
                                    return Tools.getJson(new GsonResultBean<>(-4, "系统异常"), true, true);
                                }
                            }
                        }
                    }
                }
            }
            if(StrUtil.isNotEmpty(imgUrls)){
                imgUrls = imgUrls.substring(0,imgUrls.length() - 1);
            }

            if(type == 0){
                mer.setShopLogo(imgUrls);
            }else if(type == 1){
                mer.setCodeImg(imgUrls);
            } else if(type == 2){
                mer.setIdCardImgBefore(imgUrls);
            } else if(type == 3){
                mer.setIdCardImgAfter(imgUrls);
            } else if(type == 4){
                mer.setSignImg(imgUrls);
            }
            boolean bl = merService.updateById(mer);
            if(bl){
                return Tools.getJson(new GsonResultBean<>(ResponseCode.OK, "图片上传成功"), true, true);
            }else{
                return Tools.getJson(new GsonResultBean<>(ResponseCode.FAIL, "图片上传失败"), true, true);
            }
        }catch (Exception e){
            e.printStackTrace();
            result = Tools.getJson(new GsonResultBean<>(ResponseCode.ERROR,"系统异常",e.getMessage()),true,true);
            logger.error(e.toString(), e);
            System.out.println(""+e.getMessage());
            sysErrorService.insertSelective("terminal/uploadImgRepair",e);
        }
        return result;
    }

}
